<!doctype html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Android," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="今天我们要实现一个Android中常见的上拉加载更多，至于下拉刷新同理，但是建议使用SwipeRefreshLayout这个官方提供的下拉刷新的控件，个人认为挺好用的。
下面进入正题
  实现一个类似这种的效果，首先我们分析一下，这个下拉出来的其实是一个View，在Listview低端，那我们就想办法在Listview下面加一个View 然后让其默认隐藏，当ListView下拉到低端的时候显示，加">
<meta property="og:type" content="article">
<meta property="og:title" content="Android实现ListView下拉加载更多">
<meta property="og:url" content="https://www.yanhaoblog.com/2017/02/13/Android实现ListView下拉加载更多/index.html">
<meta property="og:site_name" content="闫浩的博客">
<meta property="og:description" content="今天我们要实现一个Android中常见的上拉加载更多，至于下拉刷新同理，但是建议使用SwipeRefreshLayout这个官方提供的下拉刷新的控件，个人认为挺好用的。
下面进入正题
  实现一个类似这种的效果，首先我们分析一下，这个下拉出来的其实是一个View，在Listview低端，那我们就想办法在Listview下面加一个View 然后让其默认隐藏，当ListView下拉到低端的时候显示，加">
<meta property="og:image" content="http://img.blog.csdn.net/20151205165350456?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center">
<meta property="og:image" content="https://www.yanhaoblog.com/./images/1486969099857.jpg">
<meta property="og:updated_time" content="2017-02-13T08:12:01.051Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Android实现ListView下拉加载更多">
<meta name="twitter:description" content="今天我们要实现一个Android中常见的上拉加载更多，至于下拉刷新同理，但是建议使用SwipeRefreshLayout这个官方提供的下拉刷新的控件，个人认为挺好用的。
下面进入正题
  实现一个类似这种的效果，首先我们分析一下，这个下拉出来的其实是一个View，在Listview低端，那我们就想办法在Listview下面加一个View 然后让其默认隐藏，当ListView下拉到低端的时候显示，加">
<meta name="twitter:image" content="http://img.blog.csdn.net/20151205165350456?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"right","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://www.yanhaoblog.com/2017/02/13/Android实现ListView下拉加载更多/"/>





  <title> Android实现ListView下拉加载更多 | 闫浩的博客 </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  










  
  
    
  

  <div class="container one-collumn sidebar-position-right page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">闫浩的博客</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
    
      <p class="site-subtitle">Sometimes you got to run before you can walk</p>
    
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup">
 <span class="search-icon fa fa-search"></span>
 <input type="text" id="local-search-input">
 <div id="local-search-result"></div>
 <span class="popup-btn-close">close</span>
</div>


    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
  <link itemprop="mainEntityOfPage" href="https://www.yanhaoblog.com/2017/02/13/Android实现ListView下拉加载更多/">

  <span style="display:none" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <meta itemprop="name" content="闫浩">
    <meta itemprop="description" content="">
    <meta itemprop="image" content="/images/demo.png">
  </span>

  <span style="display:none" itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
    <meta itemprop="name" content="闫浩的博客">
    <span style="display:none" itemprop="logo" itemscope itemtype="http://schema.org/ImageObject">
      <img style="display:none;" itemprop="url image" alt="闫浩的博客" src="">
    </span>
  </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                Android实现ListView下拉加载更多
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2017-02-13T16:08:11+08:00">
                2017-02-13
              </time>
            

            

            
          </span>

          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2017/02/13/Android实现ListView下拉加载更多/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count ds-thread-count" data-thread-key="2017/02/13/Android实现ListView下拉加载更多/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          

          
          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>今天我们要实现一个Android中常见的上拉加载更多，至于下拉刷新同理，但是建议使用SwipeRefreshLayout这个官方提供的下拉刷新的控件，个人认为挺好用的。</p>
<p>下面进入正题<br><img src="http://img.blog.csdn.net/20151205165350456?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="Alt text"></p>
<p>  实现一个类似这种的效果，首先我们分析一下，这个下拉出来的其实是一个View，在Listview低端，那我们就想办法在Listview下面加一个View 然后让其默认隐藏，当ListView下拉到低端的时候显示，加载完成后再隐藏。</p>
<p> 废话不多说  上代码，我们把下边的View画出来</p>
<a id="more"></a>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line">&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;</div><div class="line">&lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;</div><div class="line">    android:background=&quot;#fff&quot;</div><div class="line">    android:layout_width=&quot;match_parent&quot;</div><div class="line">    android:layout_height=&quot;30dp&quot;&gt;</div><div class="line">   &lt;ProgressBar</div><div class="line">       android:id=&quot;@+id/pb_load&quot;</div><div class="line">       android:layout_centerInParent=&quot;true&quot;</div><div class="line">       android:layout_width=&quot;wrap_content&quot;</div><div class="line">       android:layout_height=&quot;wrap_content&quot; /&gt;</div><div class="line">&lt;/RelativeLayout&gt;</div></pre></td></tr></table></figure>
<p><img src="./images/1486969099857.jpg" alt="enter description here" title="1486969099857.jpg"></p>
<p>  这就是 我们下面要用的View，当然你也可以随意发挥加点文字 动画等等。</p>
<p>  好了，我们已经把准备工作完成，可以进行自定义控件了（想想都有点小激动呢）…<br>  首先创建一个类LoadListView然后继承ListView</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line">public class LoadListview2 extends ListView&#123;</div><div class="line">    public LoadListview2(Context context) &#123;</div><div class="line">        super(context);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    public LoadListview2(Context context, AttributeSet attrs) &#123;</div><div class="line">        super(context, attrs);</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>一定要重写两个构造方法，第一个在代码里用的时候，第二个在布局中用的时候,在此就不多讲为什么了。<br>好现在，我们已经完成第一步，构建一个属于自己的ListView，下面我们要把刚刚那个View加到ListView低端,再分析一下这个View应该什么时候加上去，嗯….当然是实例化的时候了</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">LoadListview2</span> <span class="keyword">extends</span> <span class="title">ListView</span></span>&#123;</div><div class="line">    View botton;<span class="comment">//底部布局文件</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="title">LoadListview2</span><span class="params">(Context context)</span> </span>&#123;</div><div class="line">        <span class="keyword">super</span>(context);</div><div class="line">        botton = LayoutInflater.from(context).inflate(R.layout.loadview,<span class="keyword">null</span> ,<span class="keyword">false</span>);</div><div class="line">        botton.setVisibility(View.GONE);</div><div class="line">        <span class="keyword">this</span>.addFooterView(botton);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="title">LoadListview2</span><span class="params">(Context context, AttributeSet attrs)</span> </span>&#123;</div><div class="line">        <span class="keyword">super</span>(context, attrs);</div><div class="line">        botton = LayoutInflater.from(context).inflate(R.layout.loadview,<span class="keyword">null</span> ,<span class="keyword">false</span>);</div><div class="line">        botton.setVisibility(View.GONE);</div><div class="line">        <span class="keyword">this</span>.addFooterView(botton);</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>嗯嗯嗯，这样就可以了，但是代码太low了，我们完全可以把重复代码复用起来于是乎…..</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">LoadListview2</span> <span class="keyword">extends</span> <span class="title">ListView</span></span>&#123;</div><div class="line">    View botton;<span class="comment">//底部布局文件</span></div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">initView</span><span class="params">(Context context)</span> </span>&#123;</div><div class="line">        botton = LayoutInflater.from(context).inflate(R.layout.loadview,<span class="keyword">null</span> ,<span class="keyword">false</span>);</div><div class="line">        botton.setVisibility(View.GONE);</div><div class="line">        <span class="keyword">this</span>.addFooterView(botton);</div><div class="line">    &#125;</div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="title">LoadListview2</span><span class="params">(Context context)</span> </span>&#123;</div><div class="line">        <span class="keyword">super</span>(context);</div><div class="line">        initView(context);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="title">LoadListview2</span><span class="params">(Context context, AttributeSet attrs)</span> </span>&#123;</div><div class="line">        <span class="keyword">super</span>(context, attrs);</div><div class="line">        initView(context);</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>做到这里，我们已经完成第二步了，现在View已经在ListView低端了。我默认给了一个GONE属性让他隐藏起来。<br>好了想一下我们继续应该干啥了……对，应该判断是否滑动到低端然后显示，我们去给类实现OnScrollListener这个接口，去监听ListView的滑动，然后重写onScrollStateChanged和onScroll两个方法。<br>下面 先来解释一下这两个方法的作用，和什么时候触发</p>
<p>onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount)<br>该方法只要listview发生滚动就会回调。不管用户手指是否在屏幕上。<br>firstVisibleItem：当前屏幕能见的第一个item的position从0开始<br>visibleItemCount：当前屏幕显示的item总数，不完全显示也算<br>totalItemCount：listview的item总数</p>
<p>onScrollStateChanged(AbsListView view,int scrollState)<br>该方法只要listview发生滚动就回调。同样与用户手指是否在屏幕无关。只要看第二个参数<br>scrollState：即滑动的状态。分为三种 0，1，2<br>=0 表示停止滑动的状态 SCROLL_STATE_IDLE<br>=1表示正在滚动，用户手指在屏幕上 SCROLL_STATE_TOUCH_SCROLL<br>=2表示正在滑动。用户手指已经离开屏幕 SCROLL_STATE_FLING</p>
<p>好了我们可以继续写代码了，但是我们既然实现了这个接口要设置一下在InitView方法中添加this.setOnScrollListener(this);<br>首先我们要想办法判断是否滑动到低端了，这里我的办法是这样的（当然我也是看的别人的办法 哈哈），<br>int lastVisbleItem;//当前最后一个可见的Item的位置<br>int listSize;//显示的Item个数<br>去声明两个全局变量然后</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onScroll</span><span class="params">(AbsListView view, <span class="keyword">int</span> firstVisibleItem, <span class="keyword">int</span> visibleItemCount, <span class="keyword">int</span> totalItemCount)</span> </span>&#123;</div><div class="line">        <span class="keyword">this</span>.lastVisbleItem=firstVisibleItem+visibleItemCount;<span class="comment">//(当前屏幕第一个Item在整个listView的位置+见到的Listview中的数量)</span></div><div class="line">        <span class="keyword">this</span>.listSize=totalItemCount;<span class="comment">//记录listview总数</span></div><div class="line">    &#125;</div></pre></td></tr></table></figure>
<p>lastVisbleItem这个吧如果你不理解你就想一下，比如我们一共要显示20个，一页10个，我们默认的时候应该显示第一页，那么就是0+10=10,但是如果你滑到第二页最后的时候，那么最后一页的第一个就是10，然后就会10+10=20，通过这个20等于listSIze，总共的个数，我们就能知道这个Listview是否滑动到了低端.<br>好了我们纪录完值之后，开始进行判断了</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onScrollStateChanged</span><span class="params">(AbsListView view, <span class="keyword">int</span> scrollState)</span> </span>&#123;</div><div class="line">        <span class="keyword">if</span>(<span class="keyword">this</span>.lastVisbleItem==listSize&amp;&amp;scrollState == SCROLL_STATE_IDLE)&#123;</div><div class="line">            <span class="comment">//当拉到最后一页并且停止时</span></div><div class="line">            LogUtils.e(<span class="string">"到达低端."</span>);</div><div class="line">            </div><div class="line">        &#125;</div><div class="line">    &#125;</div></pre></td></tr></table></figure>
<p>这里就是，象我刚刚解释的一样，如果滑到最后一页并且，停止滑动了，进行的操作，那么，我们就能进行刷新了。这时问题又来了，我们既然是做的一个空间，那么应该干什么，应该象Button那样，或者说SwipeRefreshLayout这个控件一样，应该调用时重写，刷新时的操作，这里我们要用到回调了，如果你不了解回调可以去看看我的另一篇博客<br><a href="https://www.yanhaoblog.com/2017/01/21/%E5%9B%9E%E8%B0%83%E6%9C%BA%E5%88%B6%E7%9A%84%E4%B8%AA%E4%BA%BA%E7%90%86%E8%A7%A3/#more">https://www.yanhaoblog.com/2017/01/21/%E5%9B%9E%E8%B0%83%E6%9C%BA%E5%88%B6%E7%9A%84%E4%B8%AA%E4%BA%BA%E7%90%86%E8%A7%A3/#more</a></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">LoadListView</span> <span class="keyword">extends</span> <span class="title">ListView</span> <span class="keyword">implements</span> <span class="title">AbsListView</span>.<span class="title">OnScrollListener</span></span>&#123;</div><div class="line">    View botton;<span class="comment">//底部布局文件</span></div><div class="line">    <span class="keyword">int</span> lastVisbleItem;<span class="comment">//当前最后一个可见的Item的位置</span></div><div class="line">    <span class="keyword">int</span> listSize;<span class="comment">//显示的Item个数</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="title">LoadListView</span><span class="params">(Context context)</span> </span>&#123;</div><div class="line">        <span class="keyword">super</span>(context);</div><div class="line">        initView(context);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">initView</span><span class="params">(Context context)</span> </span>&#123;</div><div class="line">        botton = LayoutInflater.from(context).inflate(R.layout.loadview,<span class="keyword">null</span> ,<span class="keyword">false</span>);</div><div class="line">        botton.setVisibility(View.GONE);</div><div class="line">        <span class="keyword">this</span>.addFooterView(botton);</div><div class="line">        <span class="keyword">this</span>.setOnScrollListener(<span class="keyword">this</span>);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="title">LoadListView</span><span class="params">(Context context, AttributeSet attrs)</span> </span>&#123;</div><div class="line">        <span class="keyword">super</span>(context, attrs);</div><div class="line">        initView(context);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="title">LoadListView</span><span class="params">(Context context, AttributeSet attrs, <span class="keyword">int</span> defStyleAttr)</span> </span>&#123;</div><div class="line">        <span class="keyword">super</span>(context, attrs, defStyleAttr);</div><div class="line">        initView(context);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onScrollStateChanged</span><span class="params">(AbsListView view, <span class="keyword">int</span> scrollState)</span> </span>&#123;</div><div class="line">        <span class="keyword">if</span>(<span class="keyword">this</span>.lastVisbleItem==listSize&amp;&amp;scrollState == SCROLL_STATE_IDLE)&#123;</div><div class="line">            <span class="comment">//当拉到最后一页并且停止时</span></div><div class="line">            LogUtils.e(<span class="string">"到达低端."</span>);</div><div class="line"></div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onScroll</span><span class="params">(AbsListView view, <span class="keyword">int</span> firstVisibleItem, <span class="keyword">int</span> visibleItemCount, <span class="keyword">int</span> totalItemCount)</span> </span>&#123;</div><div class="line">        <span class="keyword">this</span>.lastVisbleItem=firstVisibleItem+visibleItemCount;<span class="comment">//(当前屏幕第一个Item在整个listView的位置+见到的Listview中的数量)</span></div><div class="line">        <span class="keyword">this</span>.listSize=totalItemCount;<span class="comment">//记录listview总数</span></div><div class="line">    &#125;</div></pre></td></tr></table></figure>
<p>现在我们的自定义控件应该是这样的，我们再次基础上添加回调</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">public interface OnLoadMore&#123;</div><div class="line">        public void loadMore();</div><div class="line">    &#125;</div></pre></td></tr></table></figure>
<p>在类中添加一个内部 接口，里面有一个loadMore方法，这个方法就是当用户使用我们的自定义控件时，需要重写这个方法，我们给其解释为，当支持下拉加载更多的列表加载更多时应该干的操作。<br>这时，我们需要再加一个全局变量OnLoadMore onLoadMore;</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">LoadListview2</span> <span class="keyword">extends</span> <span class="title">ListView</span> <span class="keyword">implements</span> <span class="title">AbsListView</span>.<span class="title">OnScrollListener</span> </span>&#123;</div><div class="line">    View botton;<span class="comment">//底部布局文件</span></div><div class="line">    <span class="keyword">int</span> lastVisbleItem;<span class="comment">//当前最后一个可见的Item的位置</span></div><div class="line">    <span class="keyword">int</span> listSize;<span class="comment">//显示的Item个数</span></div><div class="line">    OnLoadMore onLoadMore;</div><div class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">initView</span><span class="params">(Context context)</span> </span>&#123;</div><div class="line">        botton = LayoutInflater.from(context).inflate(R.layout.loadview,<span class="keyword">null</span> ,<span class="keyword">false</span>);</div><div class="line">        botton.setVisibility(View.GONE);</div><div class="line">        <span class="keyword">this</span>.addFooterView(botton);</div><div class="line">    &#125;</div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="title">LoadListview2</span><span class="params">(Context context)</span> </span>&#123;</div><div class="line">        <span class="keyword">super</span>(context);</div><div class="line">        initView(context);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="title">LoadListview2</span><span class="params">(Context context, AttributeSet attrs)</span> </span>&#123;</div><div class="line">        <span class="keyword">super</span>(context, attrs);</div><div class="line">        initView(context);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onScrollStateChanged</span><span class="params">(AbsListView view, <span class="keyword">int</span> scrollState)</span> </span>&#123;</div><div class="line">        <span class="keyword">if</span>(<span class="keyword">this</span>.lastVisbleItem==listSize&amp;&amp;scrollState == SCROLL_STATE_IDLE)&#123;</div><div class="line">            <span class="comment">//当拉到最后一页并且停止时</span></div><div class="line">            LogUtils.e(<span class="string">"到达低端."</span>);</div><div class="line">            onLoadMore.loadMore();</div><div class="line">            botton.setVisibility(View.VISIBLE);</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onScroll</span><span class="params">(AbsListView view, <span class="keyword">int</span> firstVisibleItem, <span class="keyword">int</span> visibleItemCount, <span class="keyword">int</span> totalItemCount)</span> </span>&#123;</div><div class="line">        <span class="keyword">this</span>.lastVisbleItem=firstVisibleItem+visibleItemCount;<span class="comment">//(当前屏幕第一个Item在整个listView的位置+见到的Listview中的数量)</span></div><div class="line">        <span class="keyword">this</span>.listSize=totalItemCount;<span class="comment">//记录listview总数</span></div><div class="line">    &#125;</div><div class="line">    <span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">OnLoadMore</span></span>&#123;</div><div class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">loadMore</span><span class="params">()</span></span>;</div><div class="line">    &#125;</div></pre></td></tr></table></figure>
<p>这样基本功能就能实现了，但是你有没有想到，如果用户一直拉，让他一直处于最低端，一直加载更多，会不会出BUG呢，所以我做了一些优化</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">package</span> yoonh.anproject.BaseView;</div><div class="line"></div><div class="line"><span class="keyword">import</span> android.content.Context;</div><div class="line"><span class="keyword">import</span> android.util.AttributeSet;</div><div class="line"><span class="keyword">import</span> android.view.LayoutInflater;</div><div class="line"><span class="keyword">import</span> android.view.View;</div><div class="line"><span class="keyword">import</span> android.widget.AbsListView;</div><div class="line"><span class="keyword">import</span> android.widget.ListView;</div><div class="line"></div><div class="line"><span class="keyword">import</span> yoonh.anproject.R;</div><div class="line"><span class="keyword">import</span> yoonh.anproject.Utils.LogUtils;</div><div class="line"></div><div class="line"></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">LoadListview2</span> <span class="keyword">extends</span> <span class="title">ListView</span> <span class="keyword">implements</span> <span class="title">AbsListView</span>.<span class="title">OnScrollListener</span> </span>&#123;</div><div class="line">    View botton;<span class="comment">//底部布局文件</span></div><div class="line">    <span class="keyword">int</span> lastVisbleItem;<span class="comment">//当前最后一个可见的Item的位置</span></div><div class="line">    <span class="keyword">int</span> listSize;<span class="comment">//显示的Item个数</span></div><div class="line">    OnLoadMore onLoadMore;</div><div class="line">    <span class="keyword">boolean</span> isLoading;<span class="comment">//是否在加载</span></div><div class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">initView</span><span class="params">(Context context)</span> </span>&#123;</div><div class="line">        botton = LayoutInflater.from(context).inflate(R.layout.loadview,<span class="keyword">null</span> ,<span class="keyword">false</span>);</div><div class="line">        botton.setVisibility(View.GONE);</div><div class="line">        <span class="keyword">this</span>.addFooterView(botton);</div><div class="line">    &#125;</div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="title">LoadListview2</span><span class="params">(Context context)</span> </span>&#123;</div><div class="line">        <span class="keyword">super</span>(context);</div><div class="line">        initView(context);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="title">LoadListview2</span><span class="params">(Context context, AttributeSet attrs)</span> </span>&#123;</div><div class="line">        <span class="keyword">super</span>(context, attrs);</div><div class="line">        initView(context);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onScrollStateChanged</span><span class="params">(AbsListView view, <span class="keyword">int</span> scrollState)</span> </span>&#123;</div><div class="line">        <span class="keyword">if</span>(<span class="keyword">this</span>.lastVisbleItem==listSize&amp;&amp;scrollState == SCROLL_STATE_IDLE)&#123;</div><div class="line">            <span class="comment">//当拉到最后一页并且停止时</span></div><div class="line">            LogUtils.e(<span class="string">"到达低端."</span>);</div><div class="line">            <span class="keyword">if</span>(!isLoading)&#123;<span class="comment">//当确定不在加载时才会调用，以免重复加载</span></div><div class="line">                isLoading=<span class="keyword">true</span>;<span class="comment">//正在加载</span></div><div class="line">                botton.setVisibility(View.VISIBLE);<span class="comment">//显示正在记载</span></div><div class="line">                onLoadMore.loadMore();<span class="comment">//调用</span></div><div class="line">            &#125;</div><div class="line">            onLoadComplete();</div><div class="line">            botton.setVisibility(View.VISIBLE);</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onScroll</span><span class="params">(AbsListView view, <span class="keyword">int</span> firstVisibleItem, <span class="keyword">int</span> visibleItemCount, <span class="keyword">int</span> totalItemCount)</span> </span>&#123;</div><div class="line">        <span class="keyword">this</span>.lastVisbleItem=firstVisibleItem+visibleItemCount;<span class="comment">//(当前屏幕第一个Item在整个listView的位置+见到的Listview中的数量)</span></div><div class="line">        <span class="keyword">this</span>.listSize=totalItemCount;<span class="comment">//记录listview总数</span></div><div class="line">    &#125;</div><div class="line">    <span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">OnLoadMore</span></span>&#123;</div><div class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">loadMore</span><span class="params">()</span></span>;</div><div class="line">    &#125;</div><div class="line">    <span class="comment">/**</span></div><div class="line">     * 加载完成调用此方法</div><div class="line">     */</div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onLoadComplete</span><span class="params">()</span></span>&#123;</div><div class="line">        botton.setVisibility(View.GONE);<span class="comment">//隐藏</span></div><div class="line">        isLoading = <span class="keyword">false</span>;<span class="comment">//不在加载了</span></div><div class="line"></div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>我像你应该很容易能看懂，好了这样一个支持下拉加载更多的自定义控件就完成了。</p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Android/" rel="tag"># Android</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/01/21/回调机制的个人理解/" rel="next" title="回调机制的个人理解">
                <i class="fa fa-chevron-left"></i> 回调机制的个人理解
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/02/16/关于解析XML/" rel="prev" title="关于解析XML">
                关于解析XML <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>

          
          </div>
          


          
  <div class="comments" id="comments">
    
      <div class="ds-thread" data-thread-key="2017/02/13/Android实现ListView下拉加载更多/"
           data-title="Android实现ListView下拉加载更多" data-url="https://www.yanhaoblog.com/2017/02/13/Android实现ListView下拉加载更多/">
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      

      <section class="site-overview sidebar-panel sidebar-panel-active">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/demo.png"
               alt="闫浩" />
          <p class="site-author-name" itemprop="name">闫浩</p>
          <p class="site-description motion-element" itemprop="description"></p>
        </div>
        <nav class="site-state motion-element">
        
          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">14</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">5</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        


      </section>

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">闫浩</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>


<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>

<div class="powered-by">
Hosted by <a href="https://pages.coding.me" style="font-weight: bold">Coding Pages</a>
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>



        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  




  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  

  
    
  

  <script type="text/javascript">
    var duoshuoQuery = {short_name:"yanhaods"};
    (function() {
      var ds = document.createElement('script');
      ds.type = 'text/javascript';ds.async = true;
      ds.id = 'duoshuo-script';
      ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
      ds.charset = 'UTF-8';
      (document.getElementsByTagName('head')[0]
      || document.getElementsByTagName('body')[0]).appendChild(ds);
    })();
  </script>

  
    
    
    <script src="/lib/ua-parser-js/dist/ua-parser.min.js?v=0.7.9"></script>
    <script src="/js/src/hook-duoshuo.js"></script>
  












  
  
  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
      search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body").append('<div class="popoverlay">').css('overflow', 'hidden');
      $('.popup').toggle();
    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';
      $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = $( "entry", xmlResponse ).map(function() {
            return {
              title: $( "title", this ).text(),
              content: $("content",this).text(),
              url: $( "url" , this).text()
            };
          }).get();
          var $input = document.getElementById(search_id);
          var $resultContent = document.getElementById(content_id);
          $input.addEventListener('input', function(){
            var matchcounts = 0;
            var str='<ul class=\"search-result-list\">';
            var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
            $resultContent.innerHTML = "";
            if (this.value.trim().length > 1) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var content_index = [];
                var data_title = data.title.trim().toLowerCase();
                var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                var data_url = decodeURIComponent(data.url);
                var index_title = -1;
                var index_content = -1;
                var first_occur = -1;
                // only match artiles with not empty titles and contents
                if(data_title != '') {
                  keywords.forEach(function(keyword, i) {
                    index_title = data_title.indexOf(keyword);
                    index_content = data_content.indexOf(keyword);
                    if( index_title >= 0 || index_content >= 0 ){
                      isMatch = true;
                      if (i == 0) {
                        first_occur = index_content;
                      }
                    }

                  });
                }
                // show search results
                if (isMatch) {
                  matchcounts += 1;
                  str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                  var content = data.content.trim().replace(/<[^>]+>/g,"");
                  if (first_occur >= 0) {
                    // cut out 100 characters
                    var start = first_occur - 20;
                    var end = first_occur + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if(start == 0){
                      end = 50;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    var match_content = content.substring(start, end);
                    // highlight all keywords
                    keywords.forEach(function(keyword){
                      var regS = new RegExp(keyword, "gi");
                      match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                    });

                    str += "<p class=\"search-result\">" + match_content +"...</p>"
                  }
                  str += "</li>";
                }
              })};
            str += "</ul>";
            if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
            if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
            $resultContent.innerHTML = str;
          });
          proceedsearch();
        }
      });}

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".popoverlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>


  

  

  

  


</body>
</html>
